package handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import bean.User;
import service.UserService;

public class Home implements Controller {
    private UserService service;

    public void setService(UserService service) {
        this.service = service;
    }

    @Override
    public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        boolean state = false;
        ModelAndView modelAndView = new ModelAndView("home");
        HttpSession session = req.getSession();
        if (req.getMethod().equals("POST")) {
            String userName = (String) session.getAttribute("user-name");
            String oldPassword = req.getParameter("old-password");
            String newPassword = req.getParameter("new-password");
            if (User.verifyUserName(userName) && User.verifyPassword(oldPassword)
                && User.verifyPassword(newPassword)) {
                User user = new User(userName, oldPassword);
                int userId = service.verify(user);
                if (userId < 1) {
                    modelAndView.addObject("error", "更改密码失败，旧密码错误");
                } else {
                    state = service.modify(userId, newPassword);
                    if (state) {
                        modelAndView.setViewName("redirect:/logout");
                    } else {
                        modelAndView.addObject("error", "更改密码失败，未知错误");
                    }
                }
            } else {
                modelAndView.addObject("error", "用户名或密码的长度不符合规范");
            }
        }
        return modelAndView;
    }

}
